﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public delegate void NoticeCallBack(bool isYes);

public class NoticeCtrl 
{
    private static NoticeCtrl mInstance = null;
    public static NoticeCtrl Instance
    {
        get
        {
            if (mInstance == null)
            {
                mInstance = new NoticeCtrl();
            }
            return mInstance;
        }
    }

    private readonly string prefabPath = "Prefabs/noticePanel";
    private GameObject mNoticePanel = null;

    private NoticeCallBack callBack = null;
    private UIButton yesBtn = null;
    private UIButton noBtn = null;
    private UILabel titleLab = null;
    private UILabel contentLab = null;
    private UILabel yesLab = null;
    private UILabel noLab = null;

    private NoticeCtrl()
    {
        var go = Resources.Load(prefabPath) as GameObject;
        mNoticePanel = GameObject.Instantiate<GameObject>(go);
        mNoticePanel.name = "NoticeCtrl";
        var trans = mNoticePanel.transform;
        trans.SetParent(NGUITools.TryGetUIRoot().transform);
        trans.localScale = Vector3.one;
        trans.localPosition = Vector3.one;
        trans.localEulerAngles = Vector3.zero;

        InitPanel();
    }

    private void InitPanel()
    {
        var trans = mNoticePanel.transform;
        yesBtn = trans.Find("bg/okBtn").GetComponent<UIButton>();
        noBtn = trans.Find("bg/cencleBtn").GetComponent<UIButton>();
        titleLab = trans.Find("bg/titleLab").GetComponent<UILabel>();
        contentLab = trans.Find("bg/message").GetComponent<UILabel>();
        yesLab = yesBtn.transform.Find("Label").GetComponent<UILabel>();
        noLab = noBtn.transform.Find("Label").GetComponent<UILabel>();

        yesBtn.onClick.Add(new EventDelegate(() =>
        {
            OnClickBtn(true);
        }));

        noBtn.onClick.Add(new EventDelegate(() =>
        {
            OnClickBtn(false);
        }));
    }

    private void OnClickBtn(bool isYes)
    {
        Close();
        if (this.callBack != null)
        {
            this.callBack(isYes);
        }
    }

    public void Open(string content,NoticeCallBack callBack)
    {
        Open(null, content, null, null, callBack);
    }
    public void Open(string title, string content, string yesStr, string noStr, NoticeCallBack callBack)
    {
        SetPanel(title, content, yesStr, noStr);
        this.callBack = callBack;
        mNoticePanel.SetActive(true);
    }

    private void SetPanel(string title, string content, string yesStr, string noStr)
    {
        titleLab.text = string.IsNullOrEmpty(title) ? "提示" : title;
        contentLab.text = string.IsNullOrEmpty(content) ? "你确定吗？" : content;
        yesLab.text = string.IsNullOrEmpty(yesStr) ? "确定" : yesStr;
        noLab.text = string.IsNullOrEmpty(noStr) ? "取消" : noStr;
    }

    private void Close()
    {
        mNoticePanel.SetActive(false);
    }
    
}
